package com.flute.framework.monitor;

import java.io.Serializable;
import java.util.Date;
import java.util.LinkedHashMap;

import com.flute.tools.util.SerializeUtil;

public class MonitedValue implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5567749922039951259L;
	private LinkedHashMap<String, String> keyValues;
	private static final String START = "logstart";
	private static final String END = "logend";
	public static final String MESSAGE = "message";
	private String key;
	private Date date;
	private long eventId;

	public enum MonitorLevel {
		info, debug, error, warn, all
	}

	private MonitorLevel level;

	public MonitedValue() {
		this.keyValues = new LinkedHashMap<String, String>();
		this.date = new Date();
	}

	public MonitedValue(String message) {
		this.keyValues = new LinkedHashMap<String, String>();
		this.date = new Date();
		this.keyValues.put("message", message);
	}

	public boolean isMessage() {
		return keyValues.size() == 1 && keyValues.containsKey(MESSAGE);
	}

	public String getMessage() {
		return keyValues.get(MESSAGE);
	}

	public void addFieldValue(String field, String value) {
		this.keyValues.put(field, value);
	}

	public String[] getFields() {
		return keyValues.keySet().toArray(new String[] {});
	}

	public String getFieldValue(String field) {
		return keyValues.get(field);
	}

	public String toMachineString() {
		return START +
		// SerializeUtil.ObjectToByteString(this)
				MonitedValueUtil.toLogString(this) + END;
	}

	public String toManualString() {
		return "key:" + key + " date:" + date + " value:"
				+ keyValues.toString();
	}

	public static MonitedValue fromLogString(String logString) {
		if (logString.contains(START) && logString.contains(END)) {
			String value = logString.substring(logString.indexOf(START),
					logString.indexOf(END)).replace(START, "").replace(END, "");
			MonitedValue mv = MonitedValueUtil.fromLogString(value);
			if (mv == null) {
				return (MonitedValue) SerializeUtil.ByteStringToObject(value);
			} else {
				return mv;
			}
		}

		return null;
	}

	public MonitorLevel getLevel() {
		return level;
	}

	public void setLevel(MonitorLevel level) {
		this.level = level;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public long getEventId() {
		return eventId;
	}

	public void setEventId(long eventId) {
		this.eventId = eventId;
	}
}
